package com.leyou.gateway.config;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Configuration
public class RateLimitConfig {
    //定义一个KeyResolver
    @Bean
    public KeyResolver ipKeyResolver() {
        return new KeyResolver() {
            @Override
            public Mono<String> resolve(ServerWebExchange exchange) {
                //给不同的请求IP地址设置不同令牌桶
                return Mono.just(exchange.getRequest().getRemoteAddress().getHostName());

                //给不同的请求URI路径设置不同令牌桶，示例代码：
                //return Mono.just(exchange.getRequest().getURI().getPath());// 获取请求URI

                //给不同的登录用户设置不同令牌桶
                //return exchange.getPrincipal().map(Principal::getName);// 获取用户
            }
        };
        // JDK8 的Lambda写法：
        // return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
    }
}